﻿using System.IO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Runtime.Serialization.Formatters.Binary;
using Newtonsoft.Json.Linq;

namespace DH.Share.Comm
{
    [Serializable]
    public class Initinfo
    {
        public static char DIRECTORY_SEPARATOR = Path.DirectorySeparatorChar;
        public string DataBase { get; set; } = "sqlserver";
        public string CurrentPath { get; set; } = "dsdsds";
        public Initinfo(string db,string path)
        {
            DataBase = db;
            CurrentPath = path;
        }


    }
    public class JsonHelp
    {
        public JsonReader Jreader { get; private set; }
        public bool Create(string filename,Object jsonresoult)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return false;
            }
            var jsonpath = Path.Combine(Environment.CurrentDirectory, $"{filename}.json");
            FileInfo jsonfile = new FileInfo(jsonpath);
            if (jsonfile.Exists)
            {
                return false;
            }
            else
            {
                using (StreamWriter jsonstream=File.CreateText(jsonpath))
                {
                    var jss = new JsonSerializer();
                    jss.Serialize(jsonstream, jsonresoult);
                    jss.Serialize(jsonstream, jsonresoult);
                    jss.Serialize(jsonstream, jsonresoult);
                }
                return true;
            }
        }
        public bool Open(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return false;
            }
            var jsonpath = Path.Combine(Environment.CurrentDirectory, $"{filename}.json");
            if (string.IsNullOrEmpty(jsonpath))
            {
                return false;
            }
            else
            {
                using (StreamReader jsonopen = new StreamReader(jsonpath))
                {
                    using (JsonTextReader reader = new JsonTextReader(jsonopen))
                    {
                        Jreader = new JsonTextReader(new StringReader(((JObject)JToken.ReadFrom(reader)).ToString()));
                    }
                }
                return true; 
            }
        }
  
        public string ToJson(object classname)
        {
            if (classname == null)
            {
                return null;
            }
            return JsonConvert.SerializeObject(classname);
        }
    }
}
